package idp.dashboard;

import idp.communication.MessageController;
import idp.communication.MessageListener;

public class SailController extends Thread implements MessageListener
{
	private boolean _quit = false;
	private int _gzeil, _fzeil, _helling, _richting, _wind;
	private static SailController _instance;
	
	public static SailController getInstance()
	{
		if(_instance == null) _instance = new SailController();
		return _instance;
	}
	
	private SailController()
	{
		super("SailController");
	}
	
	public void start()
	{
		super.start();
		MessageController.addListener(this);
	}
	
	public void run()
	{
		while(!_quit)
		{
			int gzeil;
			
			// Grootzeil aanpassen
			if(_wind > 180)
				// Links
				gzeil = (_wind-180)/2;
			else
				// Rechts
				gzeil = _wind/2;
			
			if(gzeil != _fzeil)
			{
				MessageController.getInstance().SendMessageToDevice("fzeil "+gzeil);
				_fzeil = gzeil;
			}
			
			// Voorkom klapgijp
			if((_wind > 320 || _wind < 40) && _gzeil > 80)
				gzeil = 0;
			
			// Voorkom omgaan
			if(_helling < -35 || _helling > 35)
				gzeil += 20;
			if(_helling < -55 || _helling > 55)
				gzeil += 40;
			
			if(gzeil != _gzeil) MessageController.getInstance().SendMessageToDevice("gzeil "+gzeil);
			
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void quit()
	{
		_quit = true;
		MessageController.removeListener(this);
	}

	public void AccuMessage(int value)
	{}

	public void FokZeilMessage(int value)
	{}

	public void GrootZeilMessage(int value)
	{
		_gzeil = value;
	}

	public void HellingMessage(int value)
	{
		_helling = value;
	}

	public void RichtingMessage(int value)
	{
		_richting = value;
	}

	public void ToerenMessage(int value)
	{}

	public void WindMessage(int value)
	{
		_wind = value;
	}

	public void rfidTagMessage(long time, int tag)
	{}
}
